'use client';

import { motion } from 'framer-motion';
import { useEffect, useState } from 'react';

interface Square {
  id: number;
  size: number;
  left: number;
  opacity: number;
  rotate: number;
  delay: number;
}

export default function FloatingSquares() {
  const [squares, setSquares] = useState<Square[]>([]);

  useEffect(() => {
    const createInitialSquares = () => {
      const squares = [];
      // 减少初始方块数量到5个
      for (let i = 0; i < 5; i++) {
        squares.push({
          id: i,
          size: Math.random() * 20 + 30, // 30-50px
          left: Math.random() * window.innerWidth,
          opacity: 0.08, // 降低透明度
          rotate: Math.random() * 360,
          delay: Math.random() * 3
        });
      }
      return squares;
    };

    setSquares(createInitialSquares());

    const interval = setInterval(() => {
      const newSquare = {
        id: Date.now(),
        size: Math.random() * 20 + 30, // 保持一致的大小范围
        left: Math.random() * window.innerWidth,
        opacity: 0.08, // 保持一致的透明度
        rotate: Math.random() * 360,
        delay: 0
      };

      setSquares(prev => [...prev.slice(-4), newSquare]); // 保持最多5个方块
    }, 5000); // 增加生成间隔到5秒

    const handleResize = () => {
      setSquares(createInitialSquares());
    };
    window.addEventListener('resize', handleResize);

    return () => {
      clearInterval(interval);
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return (
    <div className="absolute inset-0 overflow-hidden pointer-events-none" style={{ zIndex: 1 }}>
      {squares.map((square) => (
        <motion.div
          key={square.id}
          className="absolute bg-white"
          initial={{ 
            bottom: '-100px',
            left: square.left,
            rotate: square.rotate,
          }}
          animate={{
            bottom: '100vh',
            left: [
              square.left,
              square.left - 30, // 减小左右摆动幅度
              square.left + 30,
              square.left
            ],
            rotate: square.rotate + 360,
          }}
          transition={{
            bottom: {
              duration: 25, // 增加上升时间，使动画更加缓慢
              delay: square.delay,
              repeat: Infinity,
              ease: 'linear'
            },
            left: {
              duration: 20, // 增加左右摆动周期
              repeat: Infinity,
              ease: 'easeInOut'
            },
            rotate: {
              duration: 20,
              repeat: Infinity,
              ease: 'linear'
            }
          }}
          style={{
            width: square.size,
            height: square.size,
            opacity: square.opacity,
            transformOrigin: 'center',
            willChange: 'transform',
          }}
        />
      ))}
    </div>
  );
} 